import config from "../config";
import api from "./request.js"


function jumpLogin() {
	let pages = getCurrentPages(); // 获取栈实例
	const perpage = pages[pages.length - 1]
	let url = '/' + perpage.route + '?'
	
	for (let i in perpage.options) {
		console.log(i, perpage.options[i])
		url = url + i + '=' + perpage.options[i] + '&'
	}
	uni.setStorageSync('pageUrl', url)
	uni.reLaunch({
		url:'/Login/loginPage'
	})
	setTimeout(() => {
		num = 1
	}, 2000)
}

let num = 1
let interceptor = {
	/* 请求拦截 */
	requestHttp(reqHttp, reject) {

		reqHttp.requestId = new Date().getTime()

		return true
	},
	/* 响应拦截处理 */
	success(response, resolve, reject) {

		if (response.data.code == 401 && num) {
			num = 0
			uni.removeStorageSync('token');
			uni.removeStorageSync('user', null);
			jumpLogin()
		}
		uni.hideLoading()
		if (response.statusCode == 200) {
			if (response.data.code == 0) {

				resolve(response.data);
			} else {
				reject(response);
			}

		} else {
			reject(response);
		}

	},
	/* 网络请求错误 */
	fail(err, resolve, reject) {
		reject(err)
	}
}

/**
 * url[, option]
 * option——选项:Object{query:'地址尾部拼接参数',baseUrl:'请求地址重置',header——请求头:Object{};
 *  */
export function request(url, option) {
	/* Object: objQr */
	function objToQuery(objQr) {
		if (!objQr) return ''
		let strData = ''
		try {
			for (var key in objQr) {
				strData += `${key}=${objQr[key]}&`
			}
			if (strData) {
				strData = '?' + strData.slice(0, -1)
			}
		} catch (e) {
			strData = ''
		}

		return strData
	}
	const httpOption = {
		url: (option.baseUrl || config.url) + url + objToQuery(option.query),
		header: Object.assign({
			/* 默认请求头 */
			'Content-Type': 'application/json;charset=UTF-8',
			'Authorization': "Bearer " + uni.getStorageSync('token')
		}, option.header),
		data: option.data || {},
		method: option.method,
		/* 如设为json，会对返回的数据做一次 JSON.parse */
		dataType: "json",
		responseType: "text",
	};

	return new Promise((resolve, reject) => {
		httpOption.success = (res) => interceptor.success(res, resolve, reject)
		httpOption.fail = (err) => interceptor.success(err, resolve, reject)
		httpOption.complete = (answer) => {}
		httpOption.option = option
		/* 同意请求处理*/
		if (interceptor.requestHttp(httpOption, reject)) {
			uni.request(httpOption);
		}

	})
}
export function get(url, data, options = {}) {
	options.url = url
	options.data = data
	options.method = 'GET'
	return request(url, options)
}
export function post(url, data, options = {}) {
	options.url = url
	options.data = data
	options.method = 'POST'
	return request(url, options)
}

export function put(url, data, options = {}) {
	options.url = url
	options.data = data
	options.method = 'PUT'
	return request(url, options)
}
export function del(url, data, options = {}) {
	options.url = url
	options.data = data
	options.method = 'DELETE'
	return request(url, options)
}